<template>
  <view class="profile-container">
    <!-- 用户信息头部 -->
    <view class="profile-header">
      <view class="header-bg"></view>
      <view class="user-info">
        <view class="avatar-section" @click="changeAvatar">
          <u-avatar 
            :src="userInfo.avatar || '/static/default-avatar.png'" 
            size="80"
          ></u-avatar>
          <view class="avatar-edit">
            <u-icon name="camera" size="16" color="white"></u-icon>
          </view>
        </view>
        <view class="user-details">
          <text class="user-name">{{ userInfo.nickname || '用户' }}</text>
          <text class="user-phone">{{ formatPhone(userInfo.phone) }}</text>
          <view class="membership-badge" :class="membershipClass">
            <u-icon :name="membershipIcon" size="12" color="white"></u-icon>
            <text class="membership-text">{{ membershipText }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 会员服务卡片 -->
    <view v-if="!isVip" class="vip-card" @click="goToVip">
      <view class="vip-content">
        <view class="vip-info">
          <text class="vip-title">开通会员享受更多服务</text>
          <text class="vip-subtitle">无限AI咨询 · 专家问答 · 个性化推荐</text>
        </view>
        <u-button type="warning" size="small">立即开通</u-button>
      </view>
    </view>
    
    <!-- 数据统计 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item" @click="goToHistory">
          <text class="stat-number">{{ userStats.consultCount }}</text>
          <text class="stat-label">咨询次数</text>
        </view>
        <view class="stat-item" @click="goToFavorites">
          <text class="stat-number">{{ userStats.favoriteCount }}</text>
          <text class="stat-label">收藏内容</text>
        </view>
        <view class="stat-item" @click="goToPoints">
          <text class="stat-number">{{ userStats.pointsCount }}</text>
          <text class="stat-label">积分余额</text>
        </view>
      </view>
    </view>
    
    <!-- 宝宝信息 -->
    <view class="baby-section">
      <view class="section-header">
        <text class="section-title">宝宝信息</text>
        <text class="add-baby" @click="addBaby">+ 添加宝宝</text>
      </view>
      
      <view v-if="babyList.length > 0" class="baby-list">
        <view 
          v-for="(baby, index) in babyList" 
          :key="index"
          class="baby-item"
          @click="editBaby(baby)"
        >
          <view class="baby-avatar">
            <u-icon :name="baby.gender === 'male' ? 'man' : 'woman'" size="24" :color="baby.gender === 'male' ? '#007aff' : '#ff69b4'"></u-icon>
          </view>
          <view class="baby-info">
            <text class="baby-name">{{ baby.name }}</text>
            <text class="baby-age">{{ calculateAge(baby.birthDate) }}</text>
          </view>
          <u-icon name="arrow-right" size="16" color="#c0c0c0"></u-icon>
        </view>
      </view>
      
      <view v-else class="no-baby">
        <u-icon name="plus-circle" size="40" color="#c0c0c0"></u-icon>
        <text class="no-baby-text">还没有添加宝宝信息</text>
        <u-button type="primary" size="small" @click="addBaby">立即添加</u-button>
      </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view 
          v-for="(item, index) in menuItems" 
          :key="index"
          class="menu-item"
          @click="goToPage(item)"
        >
          <view class="menu-left">
            <view class="menu-icon" :style="{ backgroundColor: item.iconBg }">
              <u-icon :name="item.icon" size="20" color="white"></u-icon>
            </view>
            <text class="menu-title">{{ item.title }}</text>
          </view>
          <view class="menu-right">
            <text v-if="item.badge" class="menu-badge">{{ item.badge }}</text>
            <u-icon name="arrow-right" size="16" color="#c0c0c0"></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 设置菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view 
          v-for="(item, index) in settingItems" 
          :key="index"
          class="menu-item"
          @click="goToPage(item)"
        >
          <view class="menu-left">
            <view class="menu-icon" :style="{ backgroundColor: item.iconBg }">
              <u-icon :name="item.icon" size="20" color="white"></u-icon>
            </view>
            <text class="menu-title">{{ item.title }}</text>
          </view>
          <view class="menu-right">
            <u-switch v-if="item.type === 'switch'" v-model="item.value" size="small" @change="onSwitchChange(item)"></u-switch>
            <u-icon v-else name="arrow-right" size="16" color="#c0c0c0"></u-icon>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 退出登录 -->
    <view class="logout-section">
      <u-button 
        class="logout-btn" 
        type="error" 
        size="large" 
        :plain="true"
        @click="logout"
      >
        退出登录
      </u-button>
    </view>
    
    <!-- 底部安全距离 -->
    <view class="safe-bottom"></view>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { get, post } from '@/utils/request';
import { getBabyList, calculateBabyAge, BabyInfo as ApiBabyInfo } from '@/api/baby';

// 用户信息接口
interface UserInfo {
  id: string;
  phone: string;
  nickname: string;
  avatar?: string;
  membershipType: string;
}

// 宝宝信息接口
interface BabyInfo {
  id: string;
  name: string;
  birthDate: string;
  gender: 'male' | 'female';
  weight?: number;
  height?: number;
}

// 用户统计接口
interface UserStats {
  consultCount: number;
  favoriteCount: number;
  pointsCount: number;
}

// 菜单项接口
interface MenuItem {
  title: string;
  icon: string;
  iconBg: string;
  path?: string;
  action?: string;
  badge?: string;
  type?: 'normal' | 'switch';
  value?: boolean;
}

@Component
export default class ProfilePage extends Vue {
  // 数据属性
  userInfo: UserInfo = {
    id: '',
    phone: '',
    nickname: '',
    membershipType: 'basic'
  };
  
  babyList: BabyInfo[] = [];
  
  userStats: UserStats = {
    consultCount: 0,
    favoriteCount: 0,
    pointsCount: 0
  };
  
  menuItems: MenuItem[] = [
    {
      title: '咨询历史',
      icon: 'clock',
      iconBg: '#007aff',
      path: '/pages/history/consult'
    },
    {
      title: '我的收藏',
      icon: 'heart',
      iconBg: '#ff6b35',
      path: '/pages/favorites/favorites'
    },
    {
      title: '积分商城',
      icon: 'gift',
      iconBg: '#28a745',
      path: '/pages/points/mall'
    },
    {
      title: '邀请好友',
      icon: 'share',
      iconBg: '#6f42c1',
      action: 'invite'
    },
    {
      title: '意见反馈',
      icon: 'chat-bubble',
      iconBg: '#fd7e14',
      path: '/pages/feedback/feedback'
    },
    {
      title: '客服帮助',
      icon: 'question-circle',
      iconBg: '#20c997',
      action: 'contact'
    }
  ];
  
  settingItems: MenuItem[] = [
    {
      title: '消息通知',
      icon: 'bell',
      iconBg: '#007aff',
      path: '/pages/settings/notification'
    },
    {
      title: '隐私设置',
      icon: 'lock',
      iconBg: '#6c757d',
      path: '/pages/settings/privacy'
    },
    {
      title: '推送通知',
      icon: 'volume',
      iconBg: '#28a745',
      type: 'switch',
      value: true
    },
    {
      title: '关于我们',
      icon: 'info-circle',
      iconBg: '#17a2b8',
      path: '/pages/about/about'
    }
  ];
  
  // 计算属性
  get isVip(): boolean {
    return ['premium', 'expert'].includes(this.userInfo.membershipType);
  }
  
  get membershipText(): string {
    const typeMap: { [key: string]: string } = {
      'basic': '普通用户',
      'premium': '高级会员',
      'expert': '专家会员',
      'guest': '游客模式'
    };
    return typeMap[this.userInfo.membershipType] || '普通用户';
  }
  
  get membershipClass(): string {
    return `membership-${this.userInfo.membershipType}`;
  }
  
  get membershipIcon(): string {
    const iconMap: { [key: string]: string } = {
      'basic': 'account',
      'premium': 'star',
      'expert': 'medal',
      'guest': 'eye'
    };
    return iconMap[this.userInfo.membershipType] || 'account';
  }
  
  // 生命周期
  onLoad() {
    this.loadUserInfo();
    this.loadBabyList();
    this.loadUserStats();
  }
  
  onShow() {
    this.loadUserInfo();
    this.loadBabyList();
  }
  
  onPullDownRefresh() {
    this.refreshData();
  }
  
  // 方法
  
  /**
   * 加载用户信息
   */
  loadUserInfo() {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.userInfo = userInfo;
    }
  }
  
  /**
   * 加载宝宝列表
   */
  async loadBabyList() {
    try {
      const response = await getBabyList();
      
      if (response.code === 200) {
        this.babyList = (response.data.list || []).map((baby: ApiBabyInfo) => ({
          id: baby.id || '',
          name: baby.name || '',
          birthDate: baby.birthDate || '',
          gender: baby.gender || 'male',
          weight: baby.currentWeight,
          height: baby.currentHeight
        }));
      }
    } catch (error) {
      console.error('加载宝宝列表失败:', error);
    }
  }
  
  /**
   * 加载用户统计
   */
  async loadUserStats() {
    try {
      const response = await get('/user/stats', {
        userId: this.userInfo.id
      });
      
      this.userStats = response.data || {
        consultCount: 0,
        favoriteCount: 0,
        pointsCount: 0
      };
    } catch (error) {
      console.error('加载用户统计失败:', error);
      // 使用模拟数据
      this.userStats = {
        consultCount: 15,
        favoriteCount: 8,
        pointsCount: 120
      };
    }
  }
  
  /**
   * 刷新数据
   */
  async refreshData() {
    try {
      await Promise.all([
        this.loadBabyList(),
        this.loadUserStats()
      ]);
      
      uni.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    } catch (error) {
      uni.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    } finally {
      uni.stopPullDownRefresh();
    }
  }
  
  /**
   * 格式化手机号
   */
  formatPhone(phone: string): string {
    if (!phone) return '未绑定手机号';
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
  
  /**
   * 计算宝宝年龄
   * @param birthDate 出生日期
   * @returns 年龄字符串
   */
  calculateAge(birthDate: string): string {
    return calculateBabyAge(birthDate);
  }
  
  /**
   * 更换头像
   */
  changeAvatar() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatar(tempFilePath);
      },
      fail: (error) => {
        console.error('选择图片失败:', error);
      }
    });
  }
  
  /**
   * 上传头像
   */
  async uploadAvatar(filePath: string) {
    uni.showLoading({ title: '上传中...' });
    
    try {
      // 这里应该调用上传接口
      // const uploadResult = await uploadFile('/upload/avatar', filePath);
      
      // 模拟上传成功
      this.userInfo.avatar = filePath;
      uni.setStorageSync('userInfo', this.userInfo);
      
      uni.showToast({
        title: '头像更新成功',
        icon: 'success'
      });
    } catch (error) {
      console.error('上传头像失败:', error);
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      uni.hideLoading();
    }
  }
  
  /**
   * 跳转到VIP页面
   */
  goToVip() {
    uni.navigateTo({
      url: '/pages/vip/vip'
    });
  }
  
  /**
   * 跳转到咨询历史
   */
  goToHistory() {
    uni.navigateTo({
      url: '/pages/history/consult'
    });
  }
  
  /**
   * 跳转到收藏页面
   */
  goToFavorites() {
    uni.navigateTo({
      url: '/pages/favorites/favorites'
    });
  }
  
  /**
   * 跳转到积分页面
   */
  goToPoints() {
    uni.navigateTo({
      url: '/pages/points/points'
    });
  }
  
  /**
   * 添加宝宝
   */
  addBaby() {
    uni.navigateTo({
      url: '/pages/baby/add'
    });
  }
  
  /**
   * 编辑宝宝信息
   * @param baby 宝宝信息
   */
  editBaby(baby: BabyInfo) {
    uni.navigateTo({
      url: `/pages/baby/edit?id=${baby.id}`
    });
  }
  
  /**
   * 跳转到页面
   */
  goToPage(item: MenuItem) {
    if (item.action) {
      this.handleAction(item.action);
    } else if (item.path) {
      uni.navigateTo({
        url: item.path
      });
    }
  }
  
  /**
   * 处理特殊操作
   */
  handleAction(action: string) {
    switch (action) {
      case 'invite':
        this.inviteFriends();
        break;
      case 'contact':
        this.contactService();
        break;
    }
  }
  
  /**
   * 邀请好友
   */
  inviteFriends() {
    // #ifdef MP-WEIXIN
    uni.share({
      provider: 'weixin',
      scene: 'WXSceneSession',
      type: 0,
      href: 'https://your-domain.com/invite?code=' + this.userInfo.id,
      title: '母婴AI助手',
      summary: '专业的母婴AI助手，为您提供贴心的育儿指导',
      imageUrl: '/static/share-logo.png'
    });
    // #endif
    
    // #ifdef APP-PLUS || H5
    uni.showModal({
      title: '邀请好友',
      content: '邀请码：' + this.userInfo.id,
      showCancel: false
    });
    // #endif
  }
  
  /**
   * 联系客服
   */
  contactService() {
    uni.showActionSheet({
      itemList: ['在线客服', '电话客服', '意见反馈'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            // 跳转到在线客服
            uni.navigateTo({
              url: '/pages/service/chat'
            });
            break;
          case 1:
            // 拨打客服电话
            uni.makePhoneCall({
              phoneNumber: '400-123-4567'
            });
            break;
          case 2:
            // 跳转到意见反馈
            uni.navigateTo({
              url: '/pages/feedback/feedback'
            });
            break;
        }
      }
    });
  }
  
  /**
   * 开关切换事件
   */
  onSwitchChange(item: MenuItem) {
    console.log('开关切换:', item.title, item.value);
    
    // 这里可以调用API保存设置
    uni.showToast({
      title: item.value ? '已开启' : '已关闭',
      icon: 'success'
    });
  }
  
  /**
   * 退出登录
   */
  logout() {
    uni.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          uni.removeStorageSync('isGuest');
          
          // 跳转到登录页
          uni.reLaunch({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.profile-header {
  position: relative;
  padding: 60rpx 30rpx 40rpx;
  
  .header-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 200rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  .user-info {
    position: relative;
    display: flex;
    align-items: center;
    
    .avatar-section {
      position: relative;
      margin-right: 30rpx;
      
      .avatar-edit {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 32rpx;
        height: 32rpx;
        background-color: #007aff;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2rpx solid white;
      }
    }
    
    .user-details {
      flex: 1;
      
      .user-name {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: white;
        margin-bottom: 10rpx;
      }
      
      .user-phone {
        display: block;
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-bottom: 15rpx;
      }
      
      .membership-badge {
        display: inline-flex;
        align-items: center;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        
        &.membership-basic {
          background-color: rgba(108, 117, 125, 0.8);
        }
        
        &.membership-premium {
          background-color: rgba(255, 193, 7, 0.8);
        }
        
        &.membership-expert {
          background-color: rgba(220, 53, 69, 0.8);
        }
        
        &.membership-guest {
          background-color: rgba(108, 117, 125, 0.6);
        }
        
        .membership-text {
          margin-left: 8rpx;
          font-size: 22rpx;
          color: white;
        }
      }
    }
  }
}

.vip-card {
  margin: 20rpx;
  padding: 30rpx;
  background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(255, 215, 0, 0.3);
  
  .vip-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .vip-info {
      .vip-title {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .vip-subtitle {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

.stats-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: white;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  
  .stats-grid {
    display: flex;
    justify-content: space-around;
    
    .stat-item {
      text-align: center;
      
      .stat-number {
        display: block;
        font-size: 40rpx;
        font-weight: 600;
        color: #007aff;
        margin-bottom: 10rpx;
      }
      
      .stat-label {
        font-size: 26rpx;
        color: #666;
      }
    }
  }
}

.baby-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: white;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
    
    .add-baby {
      font-size: 26rpx;
      color: #007aff;
    }
  }
  
  .baby-list {
    .baby-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .baby-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 30rpx;
        background-color: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
      }
      
      .baby-info {
        flex: 1;
        
        .baby-name {
          display: block;
          font-size: 30rpx;
          font-weight: 500;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .baby-age {
          font-size: 26rpx;
          color: #666;
        }
      }
    }
  }
  
  .no-baby {
    text-align: center;
    padding: 60rpx 0;
    
    .no-baby-text {
      display: block;
      margin: 20rpx 0 30rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}

.menu-section {
  margin: 20rpx;
  
  .menu-group {
    background-color: white;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
    overflow: hidden;
    
    .menu-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .menu-left {
        display: flex;
        align-items: center;
        
        .menu-icon {
          width: 60rpx;
          height: 60rpx;
          border-radius: 15rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
        }
        
        .menu-title {
          font-size: 30rpx;
          color: #333;
        }
      }
      
      .menu-right {
        display: flex;
        align-items: center;
        
        .menu-badge {
          margin-right: 15rpx;
          padding: 4rpx 12rpx;
          background-color: #ff4757;
          color: white;
          font-size: 22rpx;
          border-radius: 12rpx;
        }
      }
    }
  }
}

.logout-section {
  margin: 40rpx 20rpx 20rpx;
  
  .logout-btn {
    width: 100%;
    height: 100rpx;
    border-radius: 20rpx;
    font-size: 32rpx;
  }
}

.safe-bottom {
  height: 120rpx;
}
</style>